package com.centaline.androidsalesblog.activities;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.view.KeyEvent;

import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.base.BaseActivity;
import com.centaline.androidsalesblog.model.databaseobject.CityDo;
import com.centaline.androidsalesblog.service.SplashService;
import com.trello.rxlifecycle.ActivityEvent;

import org.litepal.crud.DataSupport;

import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 启动页
 */
public class SplashActivity extends BaseActivity {

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            bind = true;
            ((SplashService.SplashBinder) service).splash(splashCallback);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    private SplashService.SplashCallback splashCallback = new SplashService.SplashCallback() {
        @Override
        public void callback(int status) {
            switch (status) {
                case 0:
                    next(true);
                    break;
                case 1:
                    toast("城市列表获取失败");
                    finish();
                    break;
                default:
                    toast("出错了");
                    finish();
                    break;
            }
        }
    };

    private boolean bind;

    @Override
    protected void onDestroy() {
        if (bind) {
            unbindService(connection);
        }
        super.onDestroy();
    }

    @Override
    protected int setLayoutId() {
        return R.layout.activity_splash;
    }

    @Override
    protected void findViews() {
    }

    @Override
    protected void initViews() {
        getWindow().getDecorView().post(new Runnable() {
            @Override
            public void run() {
                Observable.create(new Observable.OnSubscribe<Integer>() {
                    @Override
                    public void call(Subscriber<? super Integer> subscriber) {
                        subscriber.onNext(DataSupport.count(CityDo.class));
                        subscriber.onCompleted();
                    }
                }).subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .compose(SplashActivity.this.<Integer>bindUntilEvent(ActivityEvent.DESTROY))
                        .map(new Func1<Integer, Boolean>() {
                            @Override
                            public Boolean call(Integer integer) {
                                return integer == 0;
                            }
                        }).subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                        if (aBoolean) {
                            bindService(new Intent(SplashActivity.this, SplashService.class), connection, BIND_AUTO_CREATE);
                        } else {
                            delayToNext(false);
                        }
                    }
                });
            }
        });
    }

    /**
     * 延时进入下一步
     */
    private void delayToNext(final boolean showGuide) {
        Observable.timer(1, TimeUnit.SECONDS)
                .compose(SplashActivity.this.<Long>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<Long>() {
                    @Override
                    public void call(Long aLong) {
                        next(showGuide);
                    }
                });
    }

    /**
     * 开启初始化Service
     */
    private void startSplashService() {
        startService(new Intent(SplashActivity.this, SplashService.class));
    }

//    private boolean checkPermissions() {
//        final boolean locationPermission = PermissionChecker.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
//                != PackageManager.PERMISSION_GRANTED;
//        final boolean storagePermission = PermissionChecker.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                != PackageManager.PERMISSION_GRANTED;
//        if (locationPermission || storagePermission) {
//            new AlertDialog.Builder(this)
//                    .setTitle(R.string.permission_title)
//                    .setMessage("定位 : 用于搜索您附近的房源.\n存储空间 : 缓存房源信息,减少流量使用.")
//                    .setPositiveButton("立即获取", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            requestPermissions(locationPermission, storagePermission);
//                        }
//                    })
//                    .create()
//                    .show();
//            return false;
//        }
//        return true;
//    }

    /**
     * 请求权限
     */
//    private void requestPermissions(boolean locationPermission, boolean storagePermission) {
//        String[] permissions = null;
//        if (locationPermission && storagePermission) {
//            permissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
//                    Manifest.permission.WRITE_EXTERNAL_STORAGE};
//        } else if (locationPermission) {
//            permissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION};
//        } else if (storagePermission) {
//            permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
//        }
//        if (permissions != null) {
//            ActivityCompat.requestPermissions(this, permissions, REQ_PERMISSION);
//        }
//    }
    private void next(boolean showGuide) {
        if (showGuide) {
            startActivity(new Intent(this, GuideActivity.class));
        } else {
            startActivity(new Intent(this, MainActivity.class));
        }
        finish();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQ_PERMISSION:
                startSplashService();
                next(true);
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return keyCode == KeyEvent.KEYCODE_BACK || super.onKeyDown(keyCode, event);
    }
}
